// ==UserScript==
// @name        pixiv thumb hack
// @namespace   null
// @include     http://www.pixiv.net/bookmark_new_illust.php*
// @include     http://www.pixiv.net/search.php*
// @include     http://www.pixiv.net/member_illust.php?id=*
// @include     http://www.pixiv.net/member_illust.php?mode=medium&illust_id=*
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
// @require     https://raw.github.com/sizzlemctwizzle/GM_config/master/gm_config.js
// @version     1
// @grant       GM_xmlhttpRequest
// @grant       GM_log
// @grant       GM_getValue
// @grant       GM_setValue
// ==/UserScript==

//BASE64编码函数
function customBase64Encode(inputStr){
	var
		bbLen=3,
		enCharLen=4,
		inpLen=inputStr.length,
		inx=0,
		jnx,
		keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
		output="",
		paddingBytes=0;
	var
		bytebuffer=new Array(bbLen),
		encodedCharIndexes=new Array(enCharLen);
	while(inx<inpLen){
		for(jnx=0;jnx<bbLen;++jnx){
			if(inx<inpLen)
				bytebuffer[jnx]=inputStr.charCodeAt(inx++)&0xff;
			else
				bytebuffer[jnx]=0;
		}
		encodedCharIndexes[0]=bytebuffer[0]>>2;
		encodedCharIndexes[1]=((bytebuffer[0]&0x3)<<4)|(bytebuffer[1]>>4);
		encodedCharIndexes[2]=((bytebuffer[1]&0x0f)<<2)|(bytebuffer[2]>>6);
		encodedCharIndexes[3]=bytebuffer[2]&0x3f;
		paddingBytes=inx-(inpLen-1);
		switch(paddingBytes){
			case 1:
				encodedCharIndexes[3]=64;
				break;
			case 2:
				encodedCharIndexes[3]=64;
				encodedCharIndexes[2]=64;
				break;
			default:
				break;
		}
		for (jnx=0;jnx<enCharLen;++jnx)
			output+=keyStr.charAt(encodedCharIndexes[jnx]);
	}
	return output;
}

function scriptInit(){
	//载入脚本后进行界面调整
	$(".popular-introduction").hide();
	$("#wrapper").width(userMainWrap);
	$(".layout-body").width(userMainWrap);
	$(".layout-wrapper").width(userMainWrap);
	$(".layout-a").width(userMainWrap);
	$(".layout-column-2").width(userMainWrap-186);
	$(".display_works").width(userMainWrap-186);
	
	$("._image-items,.display_works").on("click",".addtoFav",function(){
		var id=$(this).parent().parent().children(".work").attr("href").match(/illust\_id\=\d+$/)[0].match(/\d+/)[0];
		addFav(id);
	});
	$(".header-settings").next().append("<li><a href='javascript:;' id='gmconfig' class='item'>脚本设置</a></li>");
	$("#gmconfig").click(function(){GM_config.open();});
	$("._image-items,.display_works").prepend("<div id='hover-overlay' style='display:none;'><a href='#'><img src=''></a></div>");
	$("#hover-overlay").css('z-index','50');
	$("#hover-overlay").css('position','absolute');
	$("._image-items,.display_works").prepend("<div id='hover-overlay-manga' style='display:none;'><p></p></div>");
	$("#hover-overlay-manga").css('z-index','50');
	$("#hover-overlay-manga").css('position','absolute');
	$("#hover-overlay-manga").css('background-color','#FFF8DC');
	$("#hover-overlay-manga").css('padding','10px');
	//将缩略图区域用单独的div包裹起来以进行下一步处理
	$("._image-items").wrapInner("<div id='unHandled'></div>");
	$("#hover-overlay").hover(function(){},function(){$(this).hide()});
	$("#hover-overlay-manga").hover(function(){},function(){$(this).hide()});
	window.XMLHttpRequest = unsafeWindow.XMLHttpRequest;
}


//使用ajax实现一键加入收藏
function addFav(id){
	/* GM_xmlhttpRequest({
		method:'GET',
		url:'http://www.pixiv.net/bookmark_add.php?type=illust&illust_id='+id,
		onload:function(response){
			var pageContent=response.responseText;
			var tt=pageContent.match(/name="tt" value="\w+/)[0].match(/\w+$/)[0];
			var id=pageContent.match(/name="id" value="\w+/)[0].match(/\d+$/)[0];
			var formData=new FormData();
			formData.append("comment","");
			formData.append("from_sid","");
			formData.append("id",id);
			formData.append("mode","add");
			formData.append("restrict","0");
			formData.append("tag","");
			formData.append("tt",tt);
			formData.append("type","illust");
			GM_xmlhttpRequest({
				method:'POST',
				url:'http://www.pixiv.net/bookmark_add.php',
				data:formData,
				headers:{
					Referer:response.finalUrl
				},
				onload:function(){alert("已收藏");}
			});
		}
	}); */
	$.ajax(
		{url:'http://www.pixiv.net/bookmark_add.php?type=illust&illust_id='+id}
	).done(function(pageContent){
		var tt=pageContent.match(/name="tt" value="\w+/)[0].match(/\w+$/)[0];
		var id=pageContent.match(/name="id" value="\w+/)[0].match(/\d+$/)[0];
		var formData=new FormData();
		formData.append("comment","");
		formData.append("from_sid","");
		formData.append("id",id);
		formData.append("mode","add");
		formData.append("restrict","0");
		formData.append("tag","");
		formData.append("tt",tt);
		formData.append("type","illust");
		$.ajax({
			method:'POST',
			url:'http://www.pixiv.net/bookmark_add.php',
			data:formData,
			processData: false, 
			contentType: false
		}).done(function(){alert("已收藏");});
	});
}

//处理用id为unhandled的div包裹起来的区域
function handleThePage(){

	$(".image-item").css("float","none");
	$("img._thumbnail").css('max-width', userImageWidth-10);
	$("img._thumbnail").css('max-height', userImageHeight);
	$(".image-item").width(userImageWidth);
	setTimeout(function(){$(".image-item").height(userImageHeight+80);},1000);


	//在图片左上角设置热区探测hover事件，展示大图
	$("#unHandled img._thumbnail").before("<div class='hover-detect-overlay'></div>");
	$("#unHandled .hover-detect-overlay").css('z-index','2');
	$("#unHandled .hover-detect-overlay").css('position','absolute');
	$("#unHandled .hover-detect-overlay").offset($(this).next().offset());
	$("#unHandled .hover-detect-overlay").width(userImageWidth/4);
	$("#unHandled .hover-detect-overlay").height(userImageWidth/4);
	$("#unHandled .hover-detect-overlay").hover(function(){
		var theimg=$(this).next();
		var offset=$(this).offset();
		var pageurl=theimg.attr("pageurl");
		if(theimg.attr("mode")=="illust"){
			var nw=this.nextSibling.naturalWidth;
			var nl=offset.left-(nw-theimg.width())/2;
			if(nl<30) nl=30;
			var src=theimg.attr("src");
			$("#hover-overlay").show();
			$("#hover-overlay").offset({top:offset.top,left:nl});
			$("#hover-overlay").find("img").attr("src",src);
			$("#hover-overlay").children("a").attr("href",pageurl);
		}
		else{
			var page=theimg.attr("page");
			var generateUrl=theimg.attr("src").replace(/(\d+)_m\.(?:jpg|png)/,"mobile/$1_128x128_p");
			var body=$("#hover-overlay-manga").children("p");
			//var singleImage=theimg.attr("src").replace(/480mw\.jpg.*$/,"big_p").replace(/mobile\//,"");
			var singleImage=theimg.attr("src").replace(/(\d+)_m\.(.*)/,"$1_big_p");
			var type=theimg.attr("src").match(/\.\w+$/)[0];
			body.empty();
			var htmlString;
			for(var i=0;i<page;i++){
				htmlString="<a href='"+singleImage+i+type+"'><img class='manga-preview' src='"+generateUrl+i+".jpg'></a>";
				body.append(htmlString);	
			}
			body.find(".manga-preview").css("margin","5px");
			$("#hover-overlay-manga").show();
			$("#hover-overlay-manga").offset(offset);
			$("#hover-overlay-manga").find("a").css("float","left");
		}
	});
	

	$("#unHandled .image-item").each(function(){
		var id=$(this).children(".work").attr("href").match(/illust\_id\=\d+$/)[0].match(/\d+/)[0];
		images[id]=$(this);
		var theimage=$(this).find("img");
		theimage.attr("pageurl",$(this).children(".work").attr("href"));
		$(this).append("<p><a class='addtoFav' href='javascript:;'>加入收藏</a> <a class='toOrig' target='_blank'>进入大图</a></p>");
		theimage.find(".addtoFav").css("cursor","pointer");
		/* GM_xmlhttpRequest({
			method:'GET',
			url:$(this).children(".work").attr("href"),
			onload:function(pageContent){
				var imageURL=pageContent.responseText.match(/http:\/\/i\d\.pixiv\.net\/img\d+\/img\/[^\/]+\/\d+_m\.(?:jpg|png)/)[0];
				var imageID=pageContent.finalUrl.match(/illust\_id\=\d+$/)[0].match(/\d+/)[0];
				var mangaTest=pageContent.responseText.match("mode=manga&amp;illust_id="+imageID);
				var theimage=images[imageID].find("img");
				//theimage.attr("src",imageURL.replace(/(\d+)_m\.(?:jpg|png)/,"mobile/$1_480mw.jpg"));
				theimage.attr("src",imageURL);
				if(mangaTest==null){
					theimage.attr("mode","illust");
					images[imageID].find(".toOrig").attr("href",imageURL.replace(/_m(\.(?:jpg|png))/,"$1"));					
				}
				else{
					var html=$.parseHTML(pageContent.responseText);
					theimage.attr("mode","manga");
					theimage.attr("page",parseInt($("ul.meta",html).children("li")[1].innerHTML.match(/\d+/)[0]));
					images[imageID].find(".toOrig").attr("href","http://www.pixiv.net/member_illust.php?mode=manga&illust_id="+imageID);
				}
			}
		}); */
		$.ajax({
			url:$(this).children(".work").attr("href")}).done(function(pageContent){
				var imageURL=pageContent.match(/http:\/\/i\d\.pixiv\.net\/img\d+\/img\/[^\/]+\/\d+_m\.(?:jpg|png)/)[0];
				var imageID=imageURL.match(/\d+_m\.(?:jpg|png)$/)[0].match(/\d+/)[0];
				var mangaTest=pageContent.match("mode=manga&amp;illust_id="+imageID);
				var theimage=images[imageID].find("img");
				//theimage.attr("src",imageURL.replace(/(\d+)_m\.(?:jpg|png)/,"mobile/$1_480mw.jpg"));
				theimage.attr("src",imageURL);
				if(mangaTest==null){
					theimage.attr("mode","illust");
					images[imageID].find(".toOrig").attr("href",imageURL.replace(/_m(\.(?:jpg|png))/,"$1"));					
				}
				else{
					var html=$.parseHTML(pageContent);
					theimage.attr("mode","manga");
					theimage.attr("page",parseInt($("ul.meta",html).children("li")[1].innerHTML.match(/\d+/)[0]));
					images[imageID].find(".toOrig").attr("href","http://www.pixiv.net/member_illust.php?mode=manga&illust_id="+imageID);
				}
			});
	});

	$("#unHandled").children().unwrap();
}

//自动翻页
function autoPager(){
	if(($(document).height()-$(document).scrollTop()-$(window).height())/$(window).height()<0.5){
		$(document).unbind("scroll",autoPager);
		$("._image-items,.display_works").append("<div id='unHandled'></div>");
		currentpage=nextpage;
		/* GM_xmlhttpRequest({
			method:'GET',
			url:nextpage,
			onload:function(pageContent){
				
				var html=$.parseHTML(pageContent.responseText);
				var items=$(".image-item",html);
				if(items.length>0)
				{
					$("ul.page-list").replaceWith($("ul.page-list",html).first());
					$("#unHandled").append(items);
					nextpage=$("a[rel='next']",html).attr("href");
					handleThePage();
					if(GM_config.get('AutoPager') && nextpage) setTimeout(function(){$(document).scroll(autoPager);},1000);
				}
			}
		}); */
		$.ajax({
			url:nextpage
		}).done(function(pageContent){
			var html=$.parseHTML(pageContent);
			var items=$(".image-item",html);
			if(items.length>0)
			{
				$("ul.page-list").replaceWith($("ul.page-list",html).first());
				$("#unHandled").append(items);
				nextpage=$("a[rel='next']",html).attr("href");
				handleThePage();
				if(GM_config.get('AutoPager') && nextpage) setTimeout(function(){$(document).scroll(autoPager);},1000);
			}
		});
	}
}

GM_config.init(
{
	'id':'pixiv_thumb_hack',
	'fields':
	{
		'MainWrap':
		{
			'label':"主界面宽度",
			'type':'int',
			'default':1800
		},
		'ImageHeight':
		{
			'label':"图片框高度",
			'type':'int',
			'default':450
		},
		'ImageWidth':
		{
			'label':"图片框宽度",
			'type':'int',
			'default':300
		},
		'AutoPager':
		{
			'label':'自动翻页',
			'type':'checkbox',
			'default':true
		},
		'Swap':
		{
			'label':'替换中图为大图',
			'type':'checkbox',
			'default':true
		}
	}
});

if(!document.location.href.contains("http://www.pixiv.net/member_illust.php?mode=medium&illust_id="))
{
	var images={};
	var userMainWrap=GM_config.get('MainWrap');
	var userImageWidth=GM_config.get('ImageWidth');
	var userImageHeight=GM_config.get('ImageHeight');
	var userSwap=GM_config.get('Swap');
	var nextpage=$("a[rel='next']").attr("href");
	var currentpage=document.location.href;
	scriptInit();
	handleThePage();
	if(GM_config.get('AutoPager')&&(nextpage)) $(document).scroll(autoPager);
}
else
{
	$(".header-settings").next().append("<li><a href='javascript:;' id='gmconfig' class='item'>脚本设置</a></li>");
	$("#gmconfig").click(function(){GM_config.open();});
	var userSwap=GM_config.get('Swap');
	if($(".works_display").children()[0].href.contains("mode=big") &&userSwap){
		var bigUrl=$(".works_display").find("img").attr("src").replace(/(\d)_m(\.(?:png|jpg)).*$/,"$1$2");
		$(".works_display").find("img").attr("src",bigUrl);
		$(".works_display").find("img").css("max-width",780);
	}
}